import logging
import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from .models import User
from . import constants


logger=logging.getLogger('django')


# 先判断username是否是手机号
def get_user_by_account(account):

    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except Exception:
        return None
    else:
        return user


#自定义用户认证的后端；实现多账号登录
class UsernameMobileBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        '''
        重写用户认证的方法
        :param request:
        :param username: 用户名或者手机号
        :param password:
        :param kwargs:
        :return:
        '''
        # request为None,表示为后台登录
        if request is None:
            try:
                user=User.objects.get(username=username,is_superuser=True)
            except:
                user=None
            if user is not None and user.check_password(password):
                return user

        # 前台登录
        else:
            # 使用账号查询用户
            user=get_user_by_account(username)
            # 如果可以查询到用户，才需要去校验密码
            if user and user.check_password(password):
                # 返回user
                return user
            else:
                return None

# 生成验证邮箱的激活链接
def generate_verify_email_url(user):

    s=Serializer(settings.SECRET_KEY,constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    data={'user_id':user.id,'email':user.email}
    token=s.dumps(data)
    return settings.EMAIL_VERIFY_URL+'?token='+token.decode()

# 反序列化token,获取user
def check_verify_email_token(token):
    s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
    try:
        data=s.loads(token)
    except Exception as e:
        logger.error(e)
        return None
    else:
        user_id=data.get('user_id')
        email=data.get('email')
        try:
            user=User.objects.get(id=user_id,email=email)
        except Exception as e:
            logger.error(e)
            return None
        else:
            return user

